#include<sys/types.h>
#include<sys/socket.h>
#include<iostream>
#include<cerrno>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string>
#include<cstring>

const uint16_t post = 8080;

int main()
{
    //create socket
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cerr << "sock erro :" << errno << std::endl;
        return 1;
    }

    //bind
    struct sockaddr_in local;
    local.sin_family = 0;
    local.sin_port = htons(post);
    local.sin_addr.s_addr = INADDR_ANY;
    if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0 )
    {
        std::cerr << "bind erro :" << errno << std::endl;
        return 2;
    }

    char buff[1024];
    //server
    while(true)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        //receive
        int cnt = recvfrom(sock,buff,sizeof(buff) - 1,0,(struct sockaddr*)&client,&len);
        buff[cnt] = 0;
        std::string message; 
        message += "client #";
        message += buff;
        //回显
        std:: cout << message << std::endl;
        
        //send
        std::string s = "hello , i am server";
        sendto(sock,s.c_str(),s.size(),0,(struct sockaddr*)&client,len);
    }
    return 0;
}